package com.poetry.controller.common;
import com.poetry.domain.po.ChatMessage;
import com.poetry.exception.R;
import com.poetry.service.IChatMessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("ai")
@Tag(name = "AI交流模块管理")
public class ChatController {
    @Resource
    @Qualifier("chatClient")
    private ChatClient chatClient;
    @Resource
    @Qualifier("chatMessageServiceImpl")
    private IChatMessageService chatMessageService;

    @GetMapping("/chat")
    @Operation(summary = "AI对话")
    public R<String> generateMessage(@RequestParam String userInput, @RequestParam String conversationId) {
        // 非测试情况下返回值设为R<Flux<String>>
        return R.success("生成成功", chatClient.prompt().user(userInput)
                        .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId))
                .call().content());
        // 非测试情况下使用 .stream().content());
    }

    @GetMapping("/chat_history")
    @Operation(summary = "获取对话历史")
    public R<List<ChatMessage>> getChatHistory(@RequestParam String conversationId) {
        return chatMessageService.getChatHistory(conversationId);
    }

    @DeleteMapping("/clear_history")
    @Operation(summary = "清空对话记录")
    public R<String> clearChatHistory(@RequestParam String conversationId) {
        chatMessageService.clear(conversationId);
        return R.success("对话历史记录已清空", null);
    }
}
